<template>
  <div>
    <Drawer
      ref="modal"
      :title="$t('emailSetting.EmailTit')"
      :width="600"
      :value="show"
      :beforeClose="$_modal_decideIfClose"
      @on-close="show=false"
    >
      <Form
        ref="form"
        :labelWidth="100"
        :model="formData"
        :rules="formRule"
      >
       
        <FormItem prop="mailSender" :label="$t('emailSetting.AgentSendingMailbox')">
          <Input style="width: 200px" v-model="formData.mailSender"  :placeholder="$t('emailSetting.EmailTip')" />
        </FormItem>
        <FormItem prop="mailPassword" :label="$t('emailSetting.EmailAuthorizationCode')">
          <Input  style="width: 200px" v-model="formData.mailPassword" :placeholder="$t('emailSetting.EmailAuthorizationCodeTip')" />
        </FormItem>
        <FormItem prop="mailHost" :label="$t('emailSetting.EmailType')">
          <Input  style="width: 200px" v-model="formData.mailHost" :placeholder="$t('emailSetting.PleaseEnterEmailType')" />
          
        </FormItem>
        
        <FormItem  :label="$t('emailSetting.ReceivingEmailAddress')">
          <Form ref="formDynamic" :model="formDynamic" :label-width="80" style="width: 300px">
           
            <FormItem
            style="margin-bottom: 26px"
                  v-for="(item, index) in formDynamic.items"
                  v-if="item.status"
                  :key="index"
                  :prop="'items.' + index + '.value'"
                  :rules="[{required: true, message: $t('emailSetting.Noempty'), trigger: 'blur'}
                  ,{ type: 'email', message:$t('emailSetting.EmailTip') , trigger: 'blur' }]">
              <Row>
                  <Col span="18">
                      <Input style="width: 200px" type="email" v-model="item.value" :placeholder="$t('emailSetting.EmailTip')"></Input>
                  </Col>
                  <Col span="4" offset="1">
                      <Button @click="handleRemove(index)">{{$t('emailSetting.Del')}}</Button>
                  </Col>
              </Row>
            </FormItem>
            <FormItem>
                <Row>
                    <Col span="12">
                        <Button type="dashed" long @click="handleAdd" icon="md-add">{{$t('emailSetting.Add')}}</Button>
                    </Col>
                </Row>
            </FormItem>
            <!-- <FormItem>
                <Button type="primary" @click="handleSubmit('formDynamic')">Submit</Button>
                <Button @click="handleReset('formDynamic')" style="margin-left: 8px">Reset</Button>
            </FormItem> -->
          </Form>
        </FormItem>
        <!-- <FormItem prop="receivingEmail"  :label="$t('emailSetting.ReceivingEmailAddress')">
          <Input v-model="formData.receivingEmail" @on-enter="handleEnter" :placeholder="$t('emailSetting.ReceivingEmailAddressTip')"/>
          <Tag v-for="item in count" :key="item" :name="item" closable @on-close="handleClose2">{{ item }}</Tag>
        </FormItem> -->
        <FormItem prop="mailContext" :label="$t('emailSetting.MailContent')">
          <RadioGroup v-model="formData.mailContext">
              <Radio label="1">
                  <span>{{ $t("emailSetting.AbnormalTemperature") }}</span>
                  <div>{{ $t("emailSetting.AbnormalInformation") }}</div>
              </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem prop="mailPeriod" :label="$t('emailSetting.SendConditions')">
          <RadioGroup v-model="formData.mailPeriod">
              <Radio label="1">
                  <span>{{ $t("emailSetting.RealTime") }}</span>
              </Radio>
              <!-- <Radio label="2">
                  <span>{{ $t("emailSetting.RealTime1") }}</span>
              </Radio>
              <Radio label="3">
                  <span>{{ $t("emailSetting.RealTime2") }} </span>
              </Radio> -->
          </RadioGroup>
        </FormItem>
        <FormItem prop="mailStatus" :label="$t('emailSetting.WhetherOpen')">
          <i-switch
            v-model="formData.mailStatus"
            :true-value="1"
            :false-value="0"
            size="large"
          >
            <span slot="open">{{ $t("emailSetting.Open") }}</span>
            <span slot="close">{{ $t("emailSetting.Disabled") }}</span>
          </i-switch>
        </FormItem>
        <FormItem class="glo-btn-group">
          <Button
            type="primary"
            :loading="loading"
            @click="handleSubmit"
          >{{ $t("devicesCreate.devCreateSubmit") }}</Button>
          <Button
            @click="$_modal_close"
          >{{ $t("devicesCreate.devCreateCancel") }}</Button>
        </FormItem>
      </Form>
    </Drawer>
  </div>
</template>

<script>
import {
  create,
  getMailConfig
} from '@/api/email.js'

import modalMixin from '@/utils/mixins/modalMixin.js'

//自定义规则校验邮箱输 入
var validateEmail = (rule, value, callback) => {
  
};

export default {
  mixins: [
    modalMixin,
  ],

  props: {
    editType: {
      type: String,
      default: 'create',
    },
    editItem: Object,
  },
  data () {
    return {
      // 动态接收邮箱表单数据
      index: 1,
      formDynamic: {
        items: [
          {
            value: '',
            index: 1,
            status: 1
          }
        ]
      },
      count: [],
      recordTypes: [],
      
      show: false,
      loading: false,
      // roles: [],
      formData: {
        mailSender: '',
        mailPassword: '',
        mailHost: '',
        mailTo: '',
        mailContext:'1',
        mailPeriod:'1',
        mailStatus:1
      },

      formRule: {
        mailSender: [
          { required: true, message: this.$t('emailSetting.Noempty'), trigger: 'blur'},
          { type: 'email', message: this.$t('permissionsIndex.UserInputEmail'), trigger: 'blur' },
        ],
        mailPassword: { required: true, message: this.$t('emailSetting.Noempty'), trigger: 'blur' },
        mailHost: { required: true, message: this.$t('emailSetting.Noempty'), trigger: 'blur' },
        
      },
    }
  },
  

  mounted () {
    if(this.editType == 'update'){
      this.show=true;
    }
    
    this.getEmailSetting()
  },

  methods: {
    

    async handleSubmit () {
      const ifVlid = await this.$refs.form.validate()
      if (ifVlid && this.editType === 'update') {
        
        this.handleUpdate()
        
      }
    },
    
    async handleUpdate () {
      // const formData = this.generateFormData()
      this.handleSubmit1('formDynamic')
      
      var list=[]
      this.formDynamic.items.forEach(v=>{
        // console.log(v)
        if(v.status==1){
          list.push(v.value)
        }
      })
      
      this.formData.mailTo = list.join(',') || ''
      const { success, data } = await create(this.formData)
      if (success) {
        this.$Message.success(this.$t('devicesCreate.devCreateUpdateS'))
        // this.show = false
      } else {
        this.$Message.error(data)
      }
      this.$_modal_close()
    },
    async getEmailSetting(){
      let res=await getMailConfig()
      if(res.data.data[0]){
        this.formData=res.data.data[0]
        if(!this.formData.mailPeriod){
          this.formData.mailPeriod='1'
        }
        if(!this.formData.mailContext){
          this.formData.mailContext='1'
        }
        if(this.formData.mailTo){
          let list=this.formData.mailTo.split(',')
          // this.formDynamic.items.length=list.length;
          list.forEach((v,index)=>{
            if(index==0){
              this.formDynamic.items[0].value=v
            }
            if(index!=0){
              let data={
                value:v,
                index:index+1,
                status:1
              }
              this.formDynamic.items.push(data)
            }
          })
        }
      }
      this.formData.mailStatus=+this.formData.mailStatus
    },
    
    // 动态新增接收邮箱方法
    handleSubmit1 (name) {
        this.$refs[name].validate((valid) => {
            if (valid) {
                // this.$Message.success('Success!');
            } else {
                this.$Message.error(this.$t('emailSetting.ReceivingEmailAddressError'));
                this.handleReset('formDynamic')
            }
        })
    },
    handleReset (name) {
        this.$refs[name].resetFields();
    },
    handleAdd () {
        this.index++;
        this.formDynamic.items.push({
            value: '',
            index: this.index,
            status: 1
        });
    },
    handleRemove (index) {
        this.formDynamic.items[index].status = 0;
    }
  },
}
</script>
